package com.huihe.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 客户端工具类
 */
@Slf4j
public class ServletUtils {

    /**
     * 获取当前 HTTP 请求
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获得 ServletRequestAttributes 对象(封装了 HttpServletRequest 和 HttpServletResponse)
     * @return 一个里面有封装了 HttpServletRequest 和 HttpServletResponse 对象的 ServletRequestAttributes
     */
    public static ServletRequestAttributes getRequestAttributes() {
        // RequestContextHolder 可以获取当前线程的请求上下文,并调用 getRequestAttributes() 方法返回当前线程的 RequestAttributes 对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 生成成功响应的HTTP响应
     * @param response 渲染对象
     * @param string 待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }
}
